package com.gzy.android_douban.application;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * @author : guzy
 * @program: net-app
 * @description:
 * @date : 2022-03-26 11:32
 **/
public class AppContext extends MyApplication {

  private static AppContext instance;

  // public LoadingDialog loadingDialog;

  @Override
  public void onCreate() {
    super.onCreate();
    instance = this;
  }

  /**
   * 获得当前app运行的AppContext
   */
  public static AppContext getInstance() {
    return instance;
  }

  /**
   * ResponseBody 处理成 Json
   */
  public static String doJson(ResponseBody responseBody) {
    long contentLength = responseBody.contentLength();
    BufferedSource source = responseBody.source();
    try {
      source.request(Long.MAX_VALUE); // Buffer the entire body.
    } catch (IOException e) {
      e.printStackTrace();
    }
    Buffer buffer = source.buffer();
    Charset charset = UTF8;
    MediaType contentType = responseBody.contentType();
    if (contentType != null) {
      try {
        charset = contentType.charset(UTF8);
      } catch (UnsupportedCharsetException e) {
        e.printStackTrace();
      }
    }
    String result = "";
    // 拦截器，
    if (contentLength != 0) {
      result = buffer.clone().readString(charset);
      //            Log.e("MainActivity", " doJson====>:" + result);
    }
    return result;
  }

  private static final Charset UTF8 = Charset.forName("UTF-8");

  /***
   * 将指定路径的图片转uri
   * @param context
   * @param path ，指定图片(或文件)的路径
   * @return
   */
@SuppressLint("Range") public static Uri getMediaUriFromPath(Context context, String path) {
    Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    Cursor cursor = context.getContentResolver().query(mediaUri,
        null,
        MediaStore.Images.Media.DISPLAY_NAME + "= ?",
        new String[] { path.substring(path.lastIndexOf("/") + 1) },
        null);

    Uri uri = null;
    if (cursor.moveToFirst()) {
      uri = ContentUris.withAppendedId(mediaUri,
          cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
    }
    cursor.close();
    return uri;
  }

  /**
   * 将相册uri转换成url
   */
  public static String getRealPathFromURI(Context context, Uri contentURI) {
    String result;
    Cursor cursor = context.getContentResolver().query(contentURI,
        new String[] { MediaStore.Images.ImageColumns.DATA },//
        null, null, null);
    if (cursor == null) { result = contentURI.getPath(); } else {
      cursor.moveToFirst();
      int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
      result = cursor.getString(index);
      cursor.close();
    }
    return result;
  }

  /**
   * 将拍照的图片保存到系统相册
   */
  public static String saveImageToGallery(Context context, Bitmap bmp) {
    String fileName = "zhengfutanfang" + ".jpg";
    //检查有没有存储权限
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      AppContext.showToast("请至权限中心打开应用权限");
      return "saveError";
    } else {
      // 新建目录appDir，并把图片存到其下
      File appDir = new File(context.getExternalFilesDir(null).getPath() + "BarcodeBitmap");
      if (!appDir.exists()) {
        appDir.mkdir();
      }
      File file = new File(appDir, fileName);
      try {
        FileOutputStream fos = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      // 把file里面的图片插入到系统相册中
      try {
        MediaStore.Images.Media.insertImage(context.getContentResolver(),
            file.getAbsolutePath(), fileName, null);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }

      // 通知相册更新
      context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
      return context.getExternalFilesDir(null).getPath() + "BarcodeBitmap/" + fileName;
    }
  }



  //
  // //显示等待框
  // public void showLoading(String msg,boolean touch){
  //   if(loadingDialog == null){
  //     loadingDialog = new LoadingDialog();
  //   }else{
  //     loadingDialog.dismiss();
  //   }
  //   loadingDialog.setMsg(msg)
  //       .setOnTouchOutside(touch)
  //       .show(loadingDialog.getParentFragmentManager(),"loading");
  //   //fragment的话就把getSupportFragmentManager参数换成getChildFragmentManager
  // }
  //
  // //动态修改等待框中的文字
  // public void setLoadingMsg(String msg){
  //   if(loadingDialog == null){
  //     return;
  //   }
  //   loadingDialog.setMsg(msg);
  // }
  //
  // //隐藏等待框
  // public void hideLoading(){
  //   if(loadingDialog != null){
  //     loadingDialog.dismiss();
  //   }
  // }


}
